<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

/* include the admin UI for custom redirects */
if( wppb_check_if_add_on_is_active( 'wppb_customRedirect' ) ){
    if( file_exists( WPPB_PAID_PLUGIN_DIR .'/add-ons/custom-redirects/custom_redirects_admin.php' ) ) {
        include_once( WPPB_PAID_PLUGIN_DIR .'/add-ons/custom-redirects/custom_redirects_admin.php' );
    }
}



/**
 * Function that handles custom user redirects
 *
 * @param	string	            $type			- type of the redirect
 * @param	string	            $redirect_url   - redirect url or NULL
 * @param	null|string|object	$user			- username, user email or user data
 * @param   string              $user_role      - user role or NULL
 *
 * @return	string	$redirect_url   - custom redirect url from database (if found), otherwise is returned unchanged
 */
function wppb_custom_redirect_url( $type, $redirect_url = NULL, $user = NULL, $user_role = NULL ) {
	// variable used to skip redirects
	$skip_next_redirects = 0;

	// get custom redirects options from database
	$wppb_cr_options = array(
		'wppb_cr_user',
		'wppb_cr_role',
		'wppb_cr_global',
		'wppb_cr_default_wp_pages'
	);

	foreach( $wppb_cr_options as $option ) {
		$$option = get_option( $option, 'not_found' );
	}

	// Add subscription plan redirects option if PMS is active
	if ( function_exists( 'pms_get_subscription_plans' ) ) {
		$wppb_cr_subscription_plan = get_option( 'wppb_cr_subscription_plan', 'not_found' );
	}

	// get user data
    if( is_string( $user ) ) {
        $user_data = get_user_by( 'login', $user );
        if( isset( $user_data ) && isset( $user_data->ID ) ) {
            $user = $user_data;
        } else {
            $user_data = get_user_by( 'email', $user );
            if( isset( $user_data ) && isset( $user_data->ID ) ) {
                $user = $user_data;
            }
        }
    }

	// needed for tags
	$wppb_cr_username = NULL;

	// individual user redirects
	$wppb_current_user = wp_get_current_user();

	if( $wppb_cr_user != 'not_found' ) {
		foreach( $wppb_cr_user as $options ) {
			if( array_key_exists('idoruser', $options) && $options['idoruser'] == 'user' ) {
				if( $options['user'] == $wppb_current_user->user_login && $options['type'] == $type ) {
					$redirect_url = $options['url'];
					$skip_next_redirects = 1;
					break;
				} elseif( isset( $user ) ) {
					if( ( isset( $user->user_login ) && $options['user'] == $user->user_login && $options['type'] == $type )
						|| ( $user != NULL && $options['user'] == $user && $options['type'] == $type )
					) {
						$redirect_url = $options['url'];
						$wppb_cr_username = $user;
						$skip_next_redirects = 1;
						break;
					}
				}
			} elseif( array_key_exists('idoruser', $options) && $options['idoruser'] == 'userid' ) {
				if( (int) $options['user'] === $wppb_current_user->ID && $options['type'] == $type ) {
					$redirect_url = $options['url'];
					$skip_next_redirects = 1;
					break;
				} elseif( isset( $user ) ) {
					if( ( isset( $user->ID ) && (int) $options['user'] === $user->ID && $options['type'] == $type )
						|| ( $user != NULL && (int) $options['user'] === $user && $options['type'] == $type )
					) {
						$redirect_url = $options['url'];
						$wppb_cr_username = $user;
						$skip_next_redirects = 1;
						break;
					}
				}
			}
		}
	}

	// user role based redirects
	if( $wppb_cr_role != 'not_found' ) {
		if( $skip_next_redirects != 1 ) {
			foreach( $wppb_cr_role as $options ) {
				if( isset( $wppb_current_user ) && ! empty( $wppb_current_user->roles ) ) {
					foreach( $wppb_current_user->roles as $role => $value ) {
						if( $options['user_role'] == $value && $options['type'] == $type ) {
							$redirect_url = $options['url'];
							$skip_next_redirects = 1;
							break;
						}
					}
				}

				if( isset( $user ) ) {
					if( isset( $user->caps ) && ! empty( $user->caps ) ) {
						foreach( $user->caps as $role => $value ) {
							if( $options['user_role'] == $role && $options['type'] == $type ) {
								$redirect_url = $options['url'];
								$wppb_cr_username = $user;
								$skip_next_redirects = 1;
								break;
							}
						}
					}

					if( $user != NULL ) {
						// wp_signon return wp_error or wp_user object. So we're checking for that.
						if ( is_object($user) && !is_wp_error($user)){
							$user_data = $user;
						} else {
							$user_data = get_user_by( 'login', sanitize_user( $user ) );
						}

						if( ! isset( $user_data ) || empty( $user_data ) ) {
							$user_data = get_user_by( 'email', sanitize_email( $user ) );
						}

						if( isset( $user_data->caps ) && ! empty( $user_data->caps ) ) {
							foreach( $user_data->caps as $role => $value ) {
								if( $options['user_role'] == $role && $options['type'] == $type ) {
									$redirect_url = $options['url'];
									$wppb_cr_username = $user_data;
									$skip_next_redirects = 1;
									break;
								}
							}
						} elseif( $user_data === false && $options['type'] == 'after_registration' ) {
							if( isset( $user_role ) && $user_role !== NULL ) {
								$wppb_default_user_role = $user_role;
							} else {
								$wppb_default_user_role = get_option( 'default_role' );
							}

							if( $options['user_role'] == $wppb_default_user_role && $options['type'] == $type ) {
								$redirect_url = $options['url'];
								$wppb_cr_username = $user;
								$skip_next_redirects = 1;
								break;
							}
						}
					}
				}
			}
		}
	}

	// subscription plan based redirects
	if( function_exists( 'pms_get_subscription_plans' ) && isset( $wppb_cr_subscription_plan ) && $wppb_cr_subscription_plan != 'not_found' ) {
		if( $skip_next_redirects != 1 ) {
			foreach( $wppb_cr_subscription_plan as $options ) {
				$subscription_plan_match = false;
				
				// Check if "Any Plan" option is selected
				if( $options['subscription_plan'] === 'any' ) {
					// Check if user has any subscription
					if( isset( $_POST['subscription_plans'] ) && !empty( $_POST['subscription_plans'] ) ) {
						// During registration/checkout - if a plan is being selected, match
						$subscription_plan_match = true;
					} elseif( isset( $user ) && isset( $user->ID ) && function_exists( 'pms_get_member_subscriptions' ) ) {
                        
                        // For the Login with no subscription redirect type, we need to pass this check so the user can be redirected accordingly
                        if( $type == 'pms_no_subscription' ) {
                            $subscription_plan_match = true;
                        } else {
                            // For logged in users - check if they have any subscription
                            $subscriptions = pms_get_member_subscriptions( array( 'user_id' => $user->ID ) );
                            if( !empty( $subscriptions ) ) {
                                $subscription_plan_match = true;
                            }
                        }
					}
				} else {
					// Specific plan selected - match exact plan
					// Check if subscription_plans is in POST data (during registration/checkout)
					if( isset( $_POST['subscription_plans'] ) && !empty( $_POST['subscription_plans'] ) ) {
						$selected_subscription_plan = sanitize_text_field( $_POST['subscription_plans'] );
						
						if( $options['subscription_plan'] == $selected_subscription_plan ) {
							$subscription_plan_match = true;
						}
					}
					
					// If no POST data, check current user's subscription plan (for login redirects)
					if( !$subscription_plan_match && isset( $user ) && isset( $user->ID ) && function_exists( 'pms_get_member_subscriptions' ) ) {
						$subscriptions = pms_get_member_subscriptions( array( 'user_id' => $user->ID, 'subscription_plan_id' => $options['subscription_plan'] ) );
						
						if( !empty( $subscriptions ) ) {
							$subscription_plan_match = true;
						}
					}
				}
				
				if( $subscription_plan_match && $options['type'] == $type ) {
					$redirect_url = $options['url'];
					$skip_next_redirects = 1;
					break;
				}
			}
		}
	}

	// global redirects
	if( $wppb_cr_global != 'not_found' ) {
		if( $skip_next_redirects != 1 ) {
			if( ! empty( $wppb_cr_global ) && is_array( $wppb_cr_global ) ) {
				foreach( $wppb_cr_global as $options ) {
					if( $options['type'] == $type ) {
						$redirect_url = $options['url'];
						break;
					}
				}
			}
		}
	}

	// redirect default WordPress forms and pages
	if( $wppb_cr_default_wp_pages != 'not_found' ) {
		foreach( $wppb_cr_default_wp_pages as $options ) {
			if( $options['type'] == $type ) {
				$redirect_url = $options['url'];
				break;
			}
		}
	}

	if( ! empty( $redirect_url ) ) {
		if( wppb_check_missing_http( $redirect_url ) ) {
			$redirect_url = wppb_add_missing_http( $redirect_url );
		}

		if( ! isset( $wppb_cr_username->ID ) ) {
            if( isset( $user ) && isset( $user->ID ) ) {
                $wppb_cr_username = $user;
            } else {
                $wppb_cr_username = $wppb_current_user;
            }
		}

		$redirect_url = wppb_cr_replace_tags( $redirect_url, $wppb_cr_username );
	}

	$redirect_url = apply_filters( 'wppb_custom_redirect_url_filter', $redirect_url, $type, $redirect_url, $user );

	return $redirect_url;
}


/* the function needed to block access to the admin-panel (if requested) */
function wppb_restrict_dashboard_access() {
	$versions = array( 'Profile Builder Pro', 'Profile Builder Agency', 'Profile Builder Unlimited', 'Profile Builder Dev' );

	if( in_array( PROFILE_BUILDER, $versions ) ) {
		if( is_admin() || in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
			$wppb_module_settings = get_option( 'wppb_module_settings' );

			if( isset( $wppb_module_settings['wppb_customRedirect'] ) && $wppb_module_settings['wppb_customRedirect'] == 'show' && function_exists( 'wppb_custom_redirect_url' ) ) {
				$redirect_url = wppb_custom_redirect_url( 'dashboard_redirect' );

				if( defined( 'DOING_AJAX' ) || ( ( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) && isset( $_GET['redirect_to'] ) ) ) {
					//let wp log out the user or pass ajax calls
				} elseif( is_user_logged_in() && ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
					$redirect_url = apply_filters( 'wppb_dashboard_redirect_url', $redirect_url );

					if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
						wp_redirect( $redirect_url );

						exit;
					}
				}
			}
		}
	}
}
add_action( 'admin_init', 'wppb_restrict_dashboard_access' );


/* the function needed to redirect from default WordPress forms and pages (if requested) */
function wppb_redirect_default_wp_pages() {
	$versions = array( 'Profile Builder Pro', 'Profile Builder Agency', 'Profile Builder Unlimited', 'Profile Builder Dev' );

	if( in_array( PROFILE_BUILDER, $versions ) ) {
		if( ! is_admin() ) {
			$wppb_module_settings = get_option( 'wppb_module_settings' );

			if( isset( $wppb_module_settings['wppb_customRedirect'] ) && $wppb_module_settings['wppb_customRedirect'] == 'show' && function_exists( 'wppb_custom_redirect_url' ) ) {
				global $pagenow;

                //force wp-login.php if you accidentally get locked out
                if( $pagenow === 'wp-login.php' && ( isset( $_GET['wppb_force_wp_login'] ) || ( isset( $_SERVER['HTTP_REFERER'] )  && strpos( esc_url_raw( $_SERVER['HTTP_REFERER'] ), 'wppb_force_wp_login=true' ) !== false ) || ( isset($_REQUEST['redirect_to'])  && strpos( sanitize_text_field( $_REQUEST['redirect_to'] ), 'wppb_force_wp_login=true' ) !== false ) ) )
                    return;

				// the part for the WP register page
				if( ( $pagenow == 'wp-login.php' ) && ( isset( $_GET['action'] ) ) && ( $_GET['action'] == 'register' ) ) {
					$redirect_url = wppb_custom_redirect_url( 'register' );

					if( ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
						$redirect_url = apply_filters( 'wppb_wp_default_register_redirect_url', $redirect_url );

						if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
							wp_redirect( $redirect_url );

							exit;
						}
					}

				// the part for the WP password recovery
				} elseif( ( $pagenow == 'wp-login.php' ) && ( isset( $_GET['action'] ) ) && ( $_GET['action'] == 'lostpassword' ) ) {
					$redirect_url = wppb_custom_redirect_url( 'lostpassword' );

					if( ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
						$redirect_url = apply_filters( 'wppb_wp_default_lost_password_redirect_url', $redirect_url );

						if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
							wp_redirect( $redirect_url );

							exit;
						}
					}

				// the part for WP login; BEFORE login; this part only covers when the user isn't logged in and NOT when he just logged out
                } elseif( ( ( $pagenow == 'wp-login.php' ) && ( ! isset( $_GET['action'] ) ) && ( ! isset( $_GET['loggedout'] ) ) && ! isset( $_POST['wppb_login'] ) && ! isset( $_POST['wppb_redirect_check'] ) ) || ( isset( $_GET['redirect_to'] ) && ( ( isset( $_GET['action'] ) && $_GET['action'] != 'logout' ) || !isset( $_GET['action'] ) ) ) ) {
					$redirect_url = wppb_custom_redirect_url( 'login' );

					if( ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
						$redirect_url = apply_filters( 'wppb_wp_default_login_redirect_url', $redirect_url );

						if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
							wp_redirect( $redirect_url );

							exit;
						}
					}

				// the part for WP login; AFTER logout; this part only covers when the user was logged in and has logged out
				} elseif( ( $pagenow == 'wp-login.php' ) && ( isset( $_GET['loggedout'] ) ) && ( $_GET['loggedout'] == 'true' ) ) {
                    $redirect_url = wppb_custom_redirect_url( 'after_logout' );

                    if( ! isset( $redirect_url ) || empty( $redirect_url ) ) {
                        $redirect_url = wppb_custom_redirect_url( 'login' );

                        if( ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
                            $redirect_url = apply_filters( 'wppb_wp_default_login_redirect_url', $redirect_url );

                            if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
                                wp_redirect( $redirect_url );

                                exit;
                            }
                        }
                    } else {
                        $redirect_url = apply_filters( 'wppb_after_logout_redirect_url', $redirect_url );

                        if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
                            wp_redirect( $redirect_url );

                            exit;
                        }
                    }
				}
			}
		}
	}
}
add_action( 'init', 'wppb_redirect_default_wp_pages' );


/* the function needed to redirect from default WordPress Author Archive (if requested) */
function wppb_redirect_default_wp_author_archive() {
	$versions = array( 'Profile Builder Pro', 'Profile Builder Agency', 'Profile Builder Unlimited', 'Profile Builder Dev' );

	if( in_array( PROFILE_BUILDER, $versions ) ) {
		if( ! is_admin() ) {
			$wppb_module_settings = get_option( 'wppb_module_settings' );

			if( isset( $wppb_module_settings['wppb_customRedirect'] ) && $wppb_module_settings['wppb_customRedirect'] == 'show' && function_exists( 'wppb_custom_redirect_url' ) ) {
				if( is_author() ) {
					$redirect_url = wppb_custom_redirect_url( 'authorarchive' );

					if( ! current_user_can( apply_filters( 'wppb_custom_redirects_capability', 'manage_options' ) ) ) {
						$redirect_url = apply_filters( 'wppb_wp_default_author_archive_redirect_url', $redirect_url );

						if( isset( $redirect_url ) && ! empty( $redirect_url ) ) {
							wp_redirect( $redirect_url );

							exit;
						}
					}
				}
			}
		}
	}
}
add_action( 'get_header', 'wppb_redirect_default_wp_author_archive' );


/* function used to replace Custom Redirects tags in URLs */
function wppb_cr_replace_tags( $redirect_url, $wppb_cr_username = NULL ) {
	$wppb_cr_tags = array(
		'{{homeurl}}' => untrailingslashit( home_url() ),//this should not return a trailing slash
		'{{siteurl}}' => untrailingslashit( site_url() ),//this should not return a trailing slash
		'{{user_id}}' => ( isset( $wppb_cr_username->ID ) ? $wppb_cr_username->ID : ( $wppb_cr_username = NULL ) ),
		'{{user_nicename}}' => ( isset( $wppb_cr_username->user_nicename ) ? $wppb_cr_username->user_nicename : ( $wppb_cr_username = NULL ) ),
		'{{http_referer}}' => ( isset( $_POST['wppb_referer_url'] ) ? esc_url_raw( $_POST['wppb_referer_url'] ) : NULL ),
        '{{redirect_to}}' => ( isset( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : NULL ),
	);

	// Add PMS-specific tags if PMS is active and user is set
	if ( function_exists( 'pms_get_member_subscriptions' ) && isset( $wppb_cr_username->ID ) ) {
		$pms_tags = wppb_get_pms_redirect_tags( $wppb_cr_username->ID );
		$wppb_cr_tags = array_merge( $wppb_cr_tags, $pms_tags );
	}

	$wppb_cr_tags = apply_filters( 'wppb_cr_tags', $wppb_cr_tags );

	foreach( $wppb_cr_tags as $key => $value ) {
		if( strpos( $redirect_url, $key ) !== false ) {
			if( ( $key == '{{user_id}}' ) || ( $key == '{{user_nicename}}' ) ) {
				if( isset( $wppb_cr_username ) ) {
					$redirect_url = str_replace( $key, $value, $redirect_url );
				} else {
					$redirect_url = '';
				}
			} elseif( $key == '{{http_referer}}' && $value === NULL ) {
				if( isset( $_SERVER['HTTP_REFERER'], $_SERVER['REQUEST_URI'] ) && strpos( sanitize_text_field( $_SERVER['REQUEST_URI'] ), '/wp-login.php' ) === false ) {
					$redirect_url = str_replace( $key, esc_url_raw( $_SERVER['HTTP_REFERER'] ), $redirect_url );
                    $redirect_url = remove_query_arg( 'reauth', $redirect_url );
				} else {
					$redirect_url = '';
				}
			} else {
				$redirect_url = str_replace( $key, $value, $redirect_url );
			}
		}
	}

	return $redirect_url;
}


/* function used to redirect users after requesting a password change (if such e redirect is set in Custom Redirects) */
function wppb_redirect_after_password_change_request( $message, $user_email ){

    $user_data = get_user_by( 'email', $user_email );
    $redirect_url = wppb_get_redirect_url( 'normal', 'after_password_change_request', '', $user_data->user_login );

    if ( !empty( $redirect_url ))
        $message = '<script type="text/javascript"> window.location.href = "' . $redirect_url .'" </script>';

    return $message;
}
add_filter( 'wppb_recover_password_sent_message1', 'wppb_redirect_after_password_change_request', 10, 2 );

/**
 * Filter to integrate with PMS redirects
 * This hooks into PMS's native pms_get_redirect_url filter to handle redirects
 * 
 * PMS calls this filter right before executing wp_redirect()
 * Maps PMS form locations to Profile Builder redirect types.
 *
 * @param string $redirect_url The default PMS redirect URL
 * @param string $form_location The PMS form context
 * @return string The custom redirect URL or the original if no custom redirect is set
 */
function wppb_custom_redirects_pms_integration( $redirect_url, $form_location ) {
	// Only process if Custom Redirects is active
	if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
		return $redirect_url;
	}

	// Map PMS form locations to Profile Builder redirect types
	$location_map = array(
		'register'                    => 'after_registration',
        'new_subscription'            => 'pms_subscription_activated',
        'upgrade_subscription'        => 'pms_subscription_upgraded',
        'downgrade_subscription'      => 'pms_subscription_downgraded',
        'change_subscription'         => 'pms_subscription_changed',
		'renew_subscription'          => 'pms_subscription_renewed',
		'register_email_confirmation' => 'after_success_email_confirmation',
	);

	// Get the appropriate redirect type
	$redirect_type = isset( $location_map[$form_location] ) ? $location_map[$form_location] : $form_location;
	
	// Get current user for redirect processing
	$user = wp_get_current_user();
	if ( !$user || $user->ID == 0 ) {
		$user = null;
	}

	// Get the custom redirect URL based on subscription plan and redirect type
	$custom_redirect_url = wppb_custom_redirect_url( $redirect_type, $redirect_url, $user );
	
	// If a custom redirect is found, use it instead of the default PMS redirect
	if ( !empty( $custom_redirect_url ) ) {
		return $custom_redirect_url;
	}
	
	return $redirect_url;
}
add_filter( 'pms_get_redirect_url', 'wppb_custom_redirects_pms_integration', 20, 2 );

/**
 * Handle login redirects for all login forms (including PMS)
 * This integrates with both Profile Builder and PMS login forms to trigger custom redirects
 */
function wppb_login_redirect_handler( $redirect_to, $requested_redirect_to, $user ) {
	// Only process if Custom Redirects is active and user is not an error
	if ( !function_exists( 'wppb_custom_redirect_url' ) || is_wp_error( $user ) ) {
		return $redirect_to;
	}

	// Check if this is a PMS login form by looking for PMS-specific POST data
	$is_pms_login = ( isset( $_POST['pms_login'] ) && $_POST['pms_login'] == 1 );

	// Get custom redirect URL for after login - this will automatically handle PMS status-based redirects
	$custom_redirect_url = wppb_custom_redirect_url( 'after_login', $redirect_to, $user );
	
	// If a custom redirect is found, use it
	if ( !empty( $custom_redirect_url ) ) {
		return $custom_redirect_url;
	}

	// // For PMS login forms
	// if ( $is_pms_login && function_exists( 'pms_get_member_subscriptions' ) ) {
	// 	$pms_redirect_url = wppb_pms_login_status_redirect( $redirect_to, 'after_login', $requested_redirect_to, $user );
	// 	if ( !empty( $pms_redirect_url ) && $pms_redirect_url !== $redirect_to ) {
	// 		return $pms_redirect_url;
	// 	}
	// }

	return $redirect_to;
}
add_filter( 'login_redirect', 'wppb_login_redirect_handler', 30, 3 );


add_action( 'wp_logout', 'wppb_logout_redirect', 10 );
function wppb_logout_redirect( $user_id ){

	if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
		return;
	}

    $user = get_user_by( 'id', $user_id );
    if ( empty( $user ) || is_wp_error( $user ) ) {
        return;
    }

	$custom_redirect_url = wppb_custom_redirect_url( 'after_logout', null, $user );

    if ( !empty( $custom_redirect_url ) ) {
		wp_redirect( $custom_redirect_url );
		exit;
    }

    return;

}
/**
 * Handle password reset email sent redirects for PMS
 * 
 * @param int $user The user object
 */
add_action( 'pms_password_reset_email_sent', 'wppb_pms_password_reset_email_sent_redirect', 10 );
function wppb_pms_password_reset_email_sent_redirect( $user ){
    if ( !function_exists( 'wppb_custom_redirect_url' ) || is_wp_error( $user ) ) {
        return;
    }

    $custom_redirect_url = wppb_custom_redirect_url( 'after_password_change_request', null, $user );

    if ( !empty( $custom_redirect_url ) ) {
		wp_redirect( $custom_redirect_url );
		exit;
    }

    return;
}

/**
 * Handle password reset success redirects for PMS
 * 
 * @param int $user_id The user ID
 */
add_action( 'pms_password_reset', 'wppb_pms_password_reset_success_redirect', 10 );
function wppb_pms_password_reset_success_redirect( $user_id ){
	if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
		return;
	}

    $user = get_user_by( 'id', $user_id );
    if ( empty( $user ) || is_wp_error( $user ) ) {
        return;
    }

    $custom_redirect_url = wppb_custom_redirect_url( 'after_success_password_reset', null, $user );

    if ( !empty( $custom_redirect_url ) ) {
		wp_redirect( $custom_redirect_url );
		exit;
    }

    return;
}

/**
 * Handle edit profile form update user redirects for PMS
 * 
 * @param int $user_id The user ID
 */
add_action( 'pms_edit_profile_form_update_user', 'wppb_pms_edit_profile_form_update_user_redirect', 10, 1 );
function wppb_pms_edit_profile_form_update_user_redirect( $user_id ){
    if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
        return;
    }
    
    $user = get_user_by( 'id', $user_id );
    if ( empty( $user ) || is_wp_error( $user ) ) {
        return;
    }

    $custom_redirect_url = wppb_custom_redirect_url( 'after_edit_profile', null, $user );

    if ( !empty( $custom_redirect_url ) ) {
		wp_redirect( $custom_redirect_url );
		exit;
    }

    return;
}   

/**
 * Handle redirects when users cancel their own subscriptions through the Account form
 * 
 * @param array $member_data Member data
 * @param PMS_Member_Subscription $member_subscription The subscription that was cancelled
 */
function wppb_pms_user_cancel_subscription_redirect( $member_data, $member_subscription ) {
	// Only process if Custom Redirects is active
	if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
		return;
	}

	// Get user data
	$user = get_userdata( $member_subscription->user_id );
	if ( !$user ) {
		return;
	}

	// Get custom redirect URL for subscription cancellation
	$redirect_url = wppb_custom_redirect_url( 'pms_subscription_cancelled', null, $user, null );
	
	if ( !empty( $redirect_url ) ) {
		// Redirect immediately since this is user-initiated
		wp_redirect( $redirect_url );
		exit;
	}
}
add_action( 'pms_cancel_member_subscription_successful', 'wppb_pms_user_cancel_subscription_redirect', 10, 2 );

/**
 * Handle redirects when users abandon their subscriptions through the Account form
 * 
 * @param array $member_data Member data
 * @param PMS_Member_Subscription $member_subscription The subscription that was abandoned
 */
function wppb_pms_user_abandon_subscription_redirect( $member_data, $member_subscription ) {
	// Only process if Custom Redirects is active
	if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
		return;
	}

	// Get user data
	$user = get_userdata( $member_subscription->user_id );
	if ( !$user ) {
		return;
	}

	// Get custom redirect URL for subscription abandonment
	$redirect_url = wppb_custom_redirect_url( 'pms_subscription_abandoned', null, $user, null );
	
	if ( !empty( $redirect_url ) ) {
		// Redirect immediately since this is user-initiated
		wp_redirect( $redirect_url );
		exit;
	}
}
add_action( 'pms_abandon_member_subscription_successful', 'wppb_pms_user_abandon_subscription_redirect', 10, 2 );

/**
 * Get PMS-specific redirect tags for a user
 * 
 * @param int $user_id The user ID
 * @return array Array of PMS-specific tags
 */
function wppb_get_pms_redirect_tags( $user_id ) {
	$tags = array();
	
	// Get user's subscriptions
	$subscriptions = pms_get_member_subscriptions( array( 'user_id' => $user_id ) );
	
	if ( empty( $subscriptions ) ) {
		return $tags;
	}
	
	// Get the most recent active subscription, or the first one if none are active
	$primary_subscription = null;
	foreach ( $subscriptions as $subscription ) {
		if ( $subscription->status === 'active' ) {
			$primary_subscription = $subscription;
			break;
		}
	}
	
	// If no active subscription, use the first one
	if ( !$primary_subscription && !empty( $subscriptions ) ) {
		$primary_subscription = $subscriptions[0];
	}
	
	if ( !$primary_subscription ) {
		return $tags;
	}
	
	// Get subscription plan details
	$subscription_plan = pms_get_subscription_plan( $primary_subscription->subscription_plan_id );
	
	if ( $subscription_plan ) {
		$tags['{{subscription_plan_name}}'] = $subscription_plan->name;
		$tags['{{subscription_plan_id}}'] = $subscription_plan->id;
		$tags['{{subscription_price}}'] = $subscription_plan->price;
	} else {
		// Handle case where subscription plan doesn't exist
		$tags['{{subscription_plan_name}}'] = '';
		$tags['{{subscription_plan_id}}'] = '';
		$tags['{{subscription_price}}'] = '';
	}

	// Subscription status
	$tags['{{subscription_status}}'] = $primary_subscription->status;

	return $tags;
}

/**
 * Handle login redirects based on current subscription status
 * This integrates with Profile Builder's existing login redirect system
 * 
 * @param string $redirect_url Current redirect URL
 * @param string $redirect_type Type of redirect
 * @param string $current_redirect Current redirect URL
 * @param object $user User object
 * @return string Modified redirect URL
 */
function wppb_pms_login_status_redirect( $redirect_url, $redirect_type, $current_redirect, $user ) {
	// Only process login redirects
	if ( $redirect_type !== 'after_login' ) {
		return $redirect_url;
	}

	// Only process if PMS is active
	if ( !function_exists( 'pms_get_member_subscriptions' ) ) {
		return $redirect_url;
	}

	// Only process if user is valid
	if ( !$user || !isset( $user->ID ) ) {
		return $redirect_url;
	}

	// Get user's subscriptions
	$subscriptions = pms_get_member_subscriptions( array( 'user_id' => $user->ID ) );

	if ( empty( $subscriptions ) ) {
		// User has no subscriptions - check for no subscription redirect
		$no_subscription_redirect = wppb_custom_redirect_url( 'pms_no_subscription', $redirect_url, $user, null );
		if ( !empty( $no_subscription_redirect ) ) {
			return $no_subscription_redirect;
		}
		return $redirect_url;
	}

	// Find the primary subscription (active first, then most recent)
	$primary_subscription = null;
	$most_recent = null;

	foreach ( $subscriptions as $subscription ) {
		if ( $subscription->status === 'active' ) {
			$primary_subscription = $subscription;
			break;
		}
		if ( !$most_recent || strtotime( $subscription->start_date ) > strtotime( $most_recent->start_date ) ) {
			$most_recent = $subscription;
		}
	}

	if ( !$primary_subscription ) {
		$primary_subscription = $most_recent;
	}

	if ( !$primary_subscription ) {
		return $redirect_url;
	}

	// Check for status-specific redirects
	$status_redirect_types = array(
		'active'   => 'pms_login_active_subscription',
		'expired'  => 'pms_login_expired_subscription',
		'canceled' => 'pms_login_cancelled_subscription',
		'pending'  => 'pms_login_pending_subscription'
	);

	$status = $primary_subscription->status;
	if ( isset( $status_redirect_types[$status] ) ) {
		$status_redirect = wppb_custom_redirect_url( $status_redirect_types[$status], $redirect_url, $user, null );
		if ( !empty( $status_redirect ) ) {
			return $status_redirect;
		}
	}

	return $redirect_url;
}
add_filter( 'wppb_custom_redirect_url_filter', 'wppb_pms_login_status_redirect', 10, 4 );

/**
 * Denote PMS-related redirect types in the Custom Redirects admin interface when PMS is not active
 *
 * @param string $display_value The display value for the redirect type
 * @return string Modified display value or original if not PMS-related
 */
function wppb_pms_hide_redirects_if_no_pms( $display_value ) {
    // Only process if Custom Redirects is active
    if ( !function_exists( 'wppb_custom_redirect_url' ) ) {
        return $display_value;
    }

    // Only process if PMS is not active
    if ( function_exists( 'pms_get_subscription_plans' ) ) {
        return $display_value;
    }

    // Check if this is a PMS-related redirect type
    $pms_redirect_types = array(
        'pms_subscription_activated',
        'pms_subscription_cancelled',
        'pms_subscription_abandoned',
        'pms_subscription_renewed',
        'pms_subscription_upgraded',
        'pms_subscription_downgraded',
        'pms_subscription_changed',
        'pms_login_active_subscription',
        'pms_login_expired_subscription',
        'pms_login_cancelled_subscription',
        'pms_login_pending_subscription',
        'pms_no_subscription'
    );

    foreach ( $pms_redirect_types as $pms_type ) {
        if ( strpos( $display_value, $pms_type ) !== false ) {
            return '<pre><i>Paid Member Subscriptions inactive</i></pre>';
        }
    }

    return $display_value;
}
add_filter( 'wck_pre_displayed_value_wppb_cr_global_element_type', 'wppb_pms_hide_redirects_if_no_pms', 10, 1 );
add_filter( 'wck_pre_displayed_value_wppb_cr_role_element_type', 'wppb_pms_hide_redirects_if_no_pms', 10, 1 );
add_filter( 'wck_pre_displayed_value_wppb_cr_user_element_type', 'wppb_pms_hide_redirects_if_no_pms', 10, 1 );
add_filter( 'wck_pre_displayed_value_wppb_cr_subscription_plan_element_type', 'wppb_pms_hide_redirects_if_no_pms', 10, 1 );
